<template>
  <div class="file-manager-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>文件管理系统</span>
          <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleUploadSuccess"
            :on-error="handleUploadError" :show-file-list="false">
            <el-button type="primary">上传文件</el-button>
          </el-upload>
        </div>
      </template>

      <el-table :data="fileList" style="width: 100%" v-loading="loading">
        <el-table-column prop="fileName" label="文件名" width="240">
          <template #default="{ row }">
            <span v-if="row.fileType === 'FILE'">
              <!-- <el-icon>
                <component :is="getFileIcon(row.fileSuffix)" />
              </el-icon> -->
              {{ row.fileName }}
            </span>
            <span v-else>
              <el-icon>
                <Folder />
              </el-icon>
              {{ row.fileName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="fileSize" label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column prop="fileSuffix" label="类型" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="280" />
        <el-table-column prop="updateTime" label="更新时间" width="280" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <!-- 预览按钮 -->
            <!-- <el-button v-if="row.fileType === 'FILE' && isPreviewable(row.fileSuffix, row.fileSize)" size="small"
              @click="handlePreview(row)" type="success" :icon="View" circle title="预览" /> -->
            <el-button size="small" @click="handleDownload(row.id)" type="primary" :icon="Download" circle title="下载" />
            <el-button size="small" @click="handleDelete(row.id)" type="danger" :icon="Delete" circle title="删除" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 文件预览模态框 -->
    <!-- <FilePreviewModal
      v-model="previewVisible"
      :file-id="currentPreviewFile?.id"
      @close="handlePreviewClose"
    /> -->
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Folder,
  Download,
  Delete,
} from '@element-plus/icons-vue'
import axios from 'axios'
import { getBaseURL } from '@/utils/request'
// import { isPreviewable, getFileIcon as getFileIconUtil } from '@/utils/filePreviewUtils'
// import FilePreviewModal from './FilePreviewModal.vue'

const BASE_URL = getBaseURL() + '/api/files'


const uploadUrl = `${BASE_URL}/upload`
const fileList = ref([])
const loading = ref(false)
const headers = {
  'Content-Type': 'multipart/form-data'
}

// 预览相关状态
const previewVisible = ref(false)
const currentPreviewFile = ref(null)

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取文件列表
const fetchFileList = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${BASE_URL}/list`, {
      headers: {
        'token': localStorage.getItem('token')
      }
    })
    if (response.data.length > 0) {
      fileList.value = response.data
    } else {
      fileList.value = []
    }

  } catch (error) {
    ElMessage.error('获取文件列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 上传成功处理
const handleUploadSuccess = (response, file) => {
  if (response.success) {
    ElMessage.success('文件上传成功')
    fetchFileList()
  } else {
    ElMessage.error(response.message || '文件上传失败')
  }
}

// 上传失败处理
const handleUploadError = (error) => {
  ElMessage.error('文件上传失败: ' + error.message)
}

// 下载文件
const handleDownload = (fileId) => {
  window.open(`${BASE_URL}/download/${fileId}`, '_blank')
}

// 删除文件
const handleDelete = (fileId) => {
  ElMessageBox.confirm('确定要删除这个文件吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await axios.delete(`${BASE_URL}/${fileId}`, {
        headers: {
          'token': localStorage.getItem('token')
        }
      })
      if (response.data.success) {
        ElMessage.success('文件删除成功')
        fetchFileList()
      } else {
        ElMessage.error(response.data.message || '文件删除失败')
      }
    } catch (error) {
      ElMessage.error('文件删除失败: ' + error.message)
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 获取文件图标
// const getFileIcon = (fileSuffix) => {
//   const iconName = getFileIconUtil(fileSuffix)
//   const iconMap = {
//     'Document': Document,
//     'Picture': Picture,
//     'VideoPlay': VideoPlay,
//     'Headphone': Headphone,
//     'Files': Files
//   }
//   return iconMap[iconName] || Files
// }

// 处理文件预览
const handlePreview = (file) => {
  currentPreviewFile.value = file
  previewVisible.value = true
}

// 关闭预览
const handlePreviewClose = () => {
  previewVisible.value = false
  currentPreviewFile.value = null
}

// 初始化加载文件列表
onMounted(() => {
  fetchFileList()
})
</script>

<style scoped>
.file-manager-container {
  padding: 20px;
}

.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-demo {
  display: inline-block;
}

.el-icon {
  margin-right: 5px;
}
</style>
